package com.jyun;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class AuthCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置为不缓存
        resp.setContentType("image/jpeg");
        resp.addHeader("cache-Control","no-cache");

        //生成随机验证码
        Random random=new Random();
        String authCode="";
        for(int i=0;i<6;i++){
            authCode+=random.nextInt(10);
        }

        //验证码存入session
        HttpSession session=req.getSession();
        session.setAttribute("authCode",authCode);

        //创建图片并写入验证码
        int width =80;
        int height= 25;
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics graphics =image.getGraphics();

        Color color=new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
        graphics.setColor(color) ;//颜色

        Font font = new Font("ITALIC",Font.ITALIC,18) ;
        graphics.setFont(font);//字体
        graphics.drawString(authCode,10,height-5) ;
        graphics.dispose() ;//关闭

        //输出验证码
        ServletOutputStream servletOutputStream=resp.getOutputStream();
        ImageIO.write(image,"JPEG",servletOutputStream);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
